package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service//部门service层
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public void save(Department department){
        if(department.getId()==null){
            //添加
            departmentMapper.save(department);
        }
        //修改
        departmentMapper.update(department);
    }
    //查询上级部门
    @Override
    public List<Department> loadNextDepartment() {
        //查询一二级部门
       List<Department> departments= departmentMapper.findOneAndTwoLevel();
       //遍历一级部门
        for (Department department:departments){
            //获取二级部门
            List<Department> children = department.getChildren();
            //判断二级部门是否为空
            if(children.size()==0){//为空，设置children为null
                department.setChildren(null);
            }
            //循环迭代查询下级部门
            this.findTree(children);
        }
        return departments;
    }
    public void findTree(List<Department> departments){
        if(departments.size()!=0){
            //遍历二级部门
            for(Department department:departments){
                //通过二级部门的id查询下级部门
                List<Department> list=departmentMapper.findByParentId(department.getId());
                //判断下级部门是否为空
                if(list.size()!=0){
                    //不为空把结果值查询出来后，封装到children属性中
                    department.setChildren(list);
                    this.findTree(list);
                }
            }
        }
    }
}
